package edu.biwu.response;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 向浏览器写入一张图片
 * HttpServletResponse中的方法:
 *     public ServletOutputStream getOutputStream() throws IOException:获取一个字节输出流
 * ServletContext中的方法:
 *    public String getMimeType(String file):返回当前文件名的MIME类型
 */
@WebServlet("/resp/demo05")
public class ResponseDemo05 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取字节输出流,并且应用缓冲流
        ServletOutputStream os = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(os);

        //2.如何告诉浏览器,我要响应给你的内容是一张图片?
        String mimeType = getServletContext().getMimeType("1.jpg");
        System.out.println(mimeType);

        //3.设置响应头,目的就是告诉浏览器我即将响应给你的内容类型
        response.setHeader("Content-Type",mimeType);
        //response.setContentType(mimeType);//与setHeader等效

        //4.将文件的字节数据响应给浏览器 (利用输入流读取1.jpg的字节,然后再利用输出流写给浏览器)
        InputStream is = getServletContext().getResourceAsStream("/1.jpg");
        BufferedInputStream bis = new BufferedInputStream(is);
        int b;
        while ((b = bis.read()) != -1) {
            //最终写给浏览器
            bos.write(b);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
